package com.ias.agdis_r.activity.flight;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
//import android.support.v4.widget.SwipeRefreshLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.activity.LoginActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.activity.mine.FlightStateHistoryActivity;
import com.ias.agdis_r.activity.task.TaskDocDetailActivity;
import com.ias.agdis_r.activity.task.TaskDocListActivity;
import com.ias.agdis_r.adapter.TaskDocListAdapter;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.document.Document;
import com.ias.agdis_r.bean.document.DocumentResult;
import com.ias.agdis_r.bean.fight.FlightQueryTaskInfo;
import com.ias.agdis_r.bean.fight.FlightQueryValue;
import com.ias.agdis_r.bean.other.TempLabelBean;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.fragment.box.BoxTabFlight;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.temple.FlightTempBean;
import com.ias.agdis_r.temple.XmlHelper;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.request.BillGeneralRequest;
import com.ias.agdis_r.terminalmanager.restful.bill.vo.BillGeneralRequestVO;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.FlightRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.request.FlightSubRequest;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.FlightQueryResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.endpoint.response.FlightSubResponse;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.FlightResponseVO;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.FlightSubVO;
import com.ias.agdis_r.terminalmanager.restful.flight.vo.FlightVO;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.TerminalapplytaskRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.TerminalapplytaskResponse;
import com.ias.agdis_r.terminalmanager.restful.task.vo.TerminalApplyTaskRequestVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.flight.DataParser;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.view.flight.FlightArriveTimeView;
import com.ias.agdis_r.view.flight.FlightStateView;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SearchInfoActivity extends BaseActivity {
    /**
     * 航班唯一号参数
     */
    public static final String EXTRA_FLIGHT_SEQ = SearchDetailActivity.class.getName() + "_fseq";
    public static final String EXTRA_FLIGHT_JFK = SearchDetailActivity.class.getName() + "_jfk";
    public static final String EXTRA_FLIGHT_AOD = SearchDetailActivity.class.getName() + "_aod";
    public static final String EXTRA_TITLE = SearchDetailActivity.class.getName() + "_title";
    public static final String FLIGHT_SUBSCRIBE = SearchDetailActivity.class.getName() + "_subscribe";

    /**
     * 航班模板
     */
    private static final FlightTempBean FLIGHT_TEMP_BEAN = XmlHelper.getInstance().loadFlightXML();
    /**
     * 进港标识
     */
    public static final String ADID_A = "A";
    /**
     * 离港标识
     */
    public static final String ADID_D = "D";
    private static final String IS_SUBSCRIBED_FLAG = "Y";
    private RequestQueue requestQueue;
    private Handler handler;
    private ActionBar actionBar = null;
    /**
     * 刷新控件
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    private FlightStateView flightStateView;
    private FlightArriveTimeView arriveTimeView;
    /**
     * 模板数据填充区域
     */
    private LinearLayout templateFillArea;
    private TextView ORGNM;
    private TextView ORG3;
    private TextView DES3;
    private TextView DESNM;
    private TextView flightInfo;
    private Button subBtn, taskbtn, historyBtn;
    /**
     * 当前航班的订阅状态
     */
    private boolean isSubscribed = false;
    /**
     * 资源类型与对应名称的映射关系
     */
    private Map<String, String> rtp_map;
    /**
     * 缓存当前航班信息
     */
    private FlightQueryValue flightQueryValue;
    /**
     * 当前显示航班唯一号
     */
    private String FKE;
    private String JFK;
    private String AOD;
    /**
     * 航班信息请求消息体
     */
    private FlightRequest flightRequest = new FlightRequest();
    /**
     * 航班订阅消息体
     */
    private FlightSubRequest flightSubRequest;
    private boolean isRefresh = false;
    /**
     * 从订阅界面进入标识
     */
    private boolean isSubscribedIn;
    private RelativeLayout rlDoc;
    /**
     * 请求航班信息成功回调
     */
    private BaseOnVolleySuccessListener<FlightQueryResponse> successCallback = new BaseOnVolleySuccessListener<FlightQueryResponse>() {

        @Override
        public void onRequestSuccess(FlightQueryResponse response) {
            if (isRefresh) {
                toast(getString(R.string.refreshSucceed));
                swipeRefreshLayout.setRefreshing(false);
                isRefresh = false;
            }
            FlightResponseVO responseVO = response.getFlightResponseVO();
            if (responseVO == null) {
                finishDelayedAfterToast(getString(R.string.noResult_2), 2000);
                return;
            }
            flightQueryValue = responseVO.getResult().getFlightQueryValues().get(0);
            isSubscribed = flightQueryValue.getFlag().equals(IS_SUBSCRIBED_FLAG);
            freshUI();
            if (isSubscribedIn && JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_DOCPRINT.toString())) {
                HttpUtil.getInstance().sendRequest(initBLRQ(null, null, FKE), MessageModel.BLRQ, true);
            }
        }

        @Override
        public void onRequestFailed(BaseResponseHeader header) {
            toast(getString(R.string.serviceError));
            finish();
            swipeRefreshLayout.setRefreshing(false);
            isRefresh = false;
            UiUtil.removeLoadingUiIfExist(SearchInfoActivity.this);
        }
    };

    private BillGeneralRequest initBLRQ(String bno, String btp, String fkey) {
        BillGeneralRequest billgeneralrequest = new BillGeneralRequest();
        BillGeneralRequestVO billgeneralrequestVO = new BillGeneralRequestVO();
        if (S.isNotEmpty(btp)) {
            billgeneralrequestVO.setBtp(btp);
        }
        if (S.isNotEmpty(bno)) {
            billgeneralrequestVO.setBno(bno);
        }
        billgeneralrequestVO.setFkey(fkey);
        billgeneralrequest.setBillGeneralRequestVO(billgeneralrequestVO);
        return billgeneralrequest;
    }

    /**
     * Volley请求失败回调
     */
    private BaseOnVolleyErrorListener onErrCalback = new BaseOnVolleyErrorAdapter() {
        @Override
        public void onErrorOccurred(com.android.volley.VolleyError e) {
            String msg = "";
            if (e instanceof TimeoutError) {
                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
            } else if (e instanceof ServerError) {
                //显示接收消息异常
                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
            } else if (e instanceof NoConnectionError) {
                msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
            }
            toast(msg);
            finish();
            swipeRefreshLayout.setRefreshing(false);
            isRefresh = false;
            subBtn.setEnabled(true);
            UiUtil.removeLoadingUiIfExist(SearchInfoActivity.this);
        }
    };

    /**
     * 航班订阅成功回调
     */
    private BaseOnVolleySuccessListener<FlightSubResponse> flightSubSuccessCallback = new BaseOnVolleySuccessListener<FlightSubResponse>() {

        @Override
        public void onRequestSuccess(FlightSubResponse response) {
            try {
                if (S.isNotEmpty(response.getFlightSubResponseVO().getSubinfos().getSubflightinfos().get(0).getFlseq())) {
                    String btn_text = !isSubscribed ? getString(R.string.cancelSubscribe) : getString(R.string.subscribeFilght);
                    String toast_text = isSubscribed ? getString(R.string.cancelSubscribe) : getString(R.string.subscribeFilght);
                    subBtn.setText(btn_text);
                    isSubscribed = !isSubscribed;
                    historyBtn.setVisibility(isSubscribed ? View.VISIBLE : View.GONE);
                    toast(toast_text + getString(R.string.succeed) + getString(R.string.TRA_14));
                }
            } catch (Exception e) {
                e.printStackTrace();
                toast(getString(R.string.operatFailed));
            } finally {
                subBtn.setEnabled(true);
            }
        }

        @Override
        public void onRequestFailed(BaseResponseHeader header) {
            toast(header.getErrorMessage());
            subBtn.setEnabled(true);
        }
    };

    /**
     * 任务申请成功回调
     */
    private BaseOnVolleySuccessListener<TerminalapplytaskResponse> applyTaskSuccessCallback = new BaseOnVolleySuccessListener<TerminalapplytaskResponse>() {

        @Override
        public void onRequestSuccess(TerminalapplytaskResponse response) {
            String msg = response.getTerminalApplyTaskResponseVO().getTxt();
            if (S.isEmpty(msg)) {
                msg = response.getTerminalApplyTaskResponseVO().getEms();
            }
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
        }

        @Override
        public void onRequestFailed(BaseResponseHeader header) {
            toast(header.getErrorMessage());
        }
    };

    /**
     * 弹出提示信息以提醒用户
     *
     * @param msg
     */
    private void toast(String msg) {
        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchinfo2);
        actionBar = getActionBar();
        initActionBarSearchInfo();
        requestQueue = Volley.newRequestQueue(this);
        handler = new Handler();
        FKE = getIntent().getExtras().getString(EXTRA_FLIGHT_SEQ);
        JFK = getIntent().getExtras().getString(EXTRA_FLIGHT_JFK);
        AOD = getIntent().getExtras().getString(EXTRA_FLIGHT_AOD);
        isSubscribedIn = getIntent().getExtras().getBoolean(FLIGHT_SUBSCRIBE);
        if (S.isNotEmpty(FKE)) {
            isAllCheck(new String[]{FKE, JavaBeanManager.getInstance().getUserinfo().getEnb()});
        }
        rtp_map = DataParser.parseRtlToMap(JavaBeanManager.getInstance().getUserinfo().getRtl());
        initView();
        initFlightRequest();
        if (S.isNotEmpty(FKE) || S.isNotEmpty(JFK)) {
            query();
        }
        initEvents();
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        if (MessageModel.BLRQ.equals(serviceId)) {
            if (S.isNotEmpty(FKE)) {
                DocumentResult docList = DataManager.getInstance().getDocList(FKE);
                List<Document> documentList = docList.getDocumentList();
                if (documentList.size() > 0) {
                    rlDoc.setVisibility(View.VISIBLE);
                } else {
                    rlDoc.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    protected void updateUI(String tag) {

    }

    /**
     * 标记此fke下的所有变更消息为已读
     */
    private void isAllCheck(String[] selectionArgs) {
        // TODO Auto-generated method stub
        BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance()
                .getContext());
        int i = dbHelper.isAllCheck("select count(1) from " + BoxDBHelper.TABLE_FLIGHT + " where ischeck=0 and type='" + MessageModel.DYHB + "' and fke = ? and enb = ?", selectionArgs);
        if (i > 0) {
            dbHelper.setCheck(BoxDBHelper.TABLE_FLIGHT, "fke = ? and enb = ?", selectionArgs);
            DataManager.getInstance().setUnCheckNumber(DataManager.getInstance().getUnCheckNumber() - i);
            setResult(BoxTabFlight.RESULTCODE);
        }
        dbHelper.closeDB();
    }

    private void initEvents() {
        subBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ServiceManage.getInstance().getIsLogon()) {
                    //如果有订阅权限
                    if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_FLIGHTSUB.toString())) {
                        flightSub();
                    } else {
                        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.no_AI_T_FLIGHTSUB), false);
                    }
                } else {
                    showLoginDialog();
                }
            }
        });
        taskbtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ServiceManage.getInstance().getIsLogon()) {
                    taskDialog();
                } else {
                    showLoginDialog();
                }
            }
        });
        historyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchInfoActivity.this, FlightStateHistoryActivity.class);
                intent.putExtra(FlightStateHistoryActivity.EXTRA_FLIGHT_FKE, "" + flightQueryValue.getFKE());
                startActivity(intent);
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                isRefresh = true;
                query();
            }
        });
    }

    /**
     * 弹出对话框提醒用户没有登录，按登录按钮启动登录流程
     */
    private void showLoginDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_info).setTitle(getString(R.string.loginTitle))
                .setMessage(getString(R.string.isLogin)).setPositiveButton(getString(R.string.login), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(SearchInfoActivity.this, LoginActivity.class));
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 服务器航班订阅请求
     */
    private void flightSub() {
        subBtn.setEnabled(false);
        initFlightSubRequest();
        flightSubRequest.getFlightSubVO().setOpe(isSubscribed ? "N" : "Y");
        Request<FlightSubResponse> request = null;
        try {
            request = new GsonRequest<FlightSubResponse>(RestfulUri.getUri(MessageModel.HBDY),
                    FlightSubResponse.class, DataManager.getInstance().getMapper().writeValueAsString(flightSubRequest), flightSubSuccessCallback,
                    this.onErrCalback);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        requestQueue.add(request);
    }

    /**
     * 初始化View
     */
    private void initView() {
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.flight_swipe_refresh_view);
        flightStateView = (FlightStateView) findViewById(R.id.flight_state);
        arriveTimeView = (FlightArriveTimeView) findViewById(R.id.flight_arrive_time_view);
        templateFillArea = (LinearLayout) findViewById(R.id.flight_template_fill_area);
        subBtn = (Button) findViewById(R.id.flightinfo_subbtn);
        taskbtn = (Button) findViewById(R.id.flightinfo_taskbtn);
        historyBtn = (Button) findViewById(R.id.flightinfo_history);
        this.ORGNM = (TextView) findViewById(R.id.flightinfo_ORGNM);
        this.ORG3 = (TextView) findViewById(R.id.flightinfo_ORG3);
        this.DES3 = (TextView) findViewById(R.id.flightinfo_DES3);
        this.DESNM = (TextView) findViewById(R.id.flightinfo_DESNM);
        this.flightInfo = (TextView) findViewById(R.id.fl_info);
        rlDoc = (RelativeLayout) arriveTimeView.findViewById(R.id.rl_doc);
        rlDoc.setVisibility(View.GONE);
        rlDoc.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> taskdata = new HashMap<String, Object>();
                taskdata.put(MessageModel.strTxtValue[MessageModel.nFKE], flightQueryValue.getFKE());
                taskdata.put(MessageModel.strTxtValue[MessageModel.nFLN], flightQueryValue.getFLN());
                taskdata.put(MessageModel.strTxtValue[MessageModel.nAOD], flightQueryValue.getAOD());
                Intent billintent = new Intent(SearchInfoActivity.this, TaskDocListActivity.class);
                billintent.putExtra("taskdata", taskdata);
                startActivity(billintent);
            }
        });
    }

    /**
     * 初始化航班查询请求信息体（请求当前需要显示的航班航班）
     */
    private void initFlightRequest() {
        flightRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.QFIQ));
        FlightVO flightVO = new FlightVO();
        if (S.isNotEmpty(JFK)) {
            flightVO.setRkey(JFK);
            flightVO.setAod(AOD);
        } else {
            flightVO.setFkey(FKE);
        }
        flightVO.setDir("N");
        flightVO.setIdx("0");
        flightVO.setNum("1");
        flightRequest.setFlightVO(flightVO);
    }

    /**
     * 初始化航班订阅请求消息体
     */
    private void initFlightSubRequest() {
        if (flightSubRequest == null) {
            flightSubRequest = new FlightSubRequest();
            flightSubRequest.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.HBDY));
            FlightSubVO flightSubVO = new FlightSubVO();
            if (flightQueryValue != null) {
                flightSubVO.setFke(flightQueryValue.getFKE());
                flightSubVO.setFln(flightQueryValue.getFLN());
            }
            flightSubRequest.setFlightSubVO(flightSubVO);
        }
    }

    /**
     * 请求当前航班信息
     */
    private void query() {
        if (!swipeRefreshLayout.isRefreshing()) {
            UiUtil.showFlightInfoLoadingUi(this);
        }
        Request<FlightQueryResponse> request = null;
        try {
            request = new GsonRequest<FlightQueryResponse>(
                    RestfulUri.getUri(MessageModel.QFIQ), FlightQueryResponse.class, DataManager.getInstance().getMapper().writeValueAsString(flightRequest),
                    successCallback, this.onErrCalback);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        requestQueue.add(request);
    }

    /**
     * 刷新界面显示信息（航班信息保存于flightQueryValue）
     */
    private void freshUI() {
        flightStateView.setFlightQueryValue(this.flightQueryValue);
        arriveTimeView.setFlightQueryValue(this.flightQueryValue);
        subBtn.setText(isSubscribed ? getString(R.string.cancelSubscribe) : getString(R.string.subscribeFilght));
        historyBtn.setVisibility(isSubscribed ? View.VISIBLE : View.GONE);
        this.setORGNM(flightQueryValue.getOAN());
        this.setDESNM(flightQueryValue.getDAN());
        this.AOD = S.valueOf(flightQueryValue.getAOD());
        StringBuilder info = new StringBuilder(ORGNM.getText()).append("(").append(ORG3.getText()).append(") → (").append(DES3.getText()).append(")").append(DESNM.getText());
        this.flightInfo.setText(info.toString());
        Map<String, TempLabelBean> map;
        switch (flightQueryValue.getAOD()) {
            case ADID_A:
                map = FLIGHT_TEMP_BEAN.groupA;
                break;
            case ADID_D:
                map = FLIGHT_TEMP_BEAN.groupD;
                break;
            default:
                return;
        }
        showTemplateData(map);
        UiUtil.removeLoadingUiIfExist(this);
    }

    /**
     * 显示模板数据
     *
     * @param template
     */
    private void showTemplateData(Map<String, TempLabelBean> template) {
        templateFillArea.removeAllViews();
        Object[] labelBeans = template.values().toArray();
        LinearLayout container = null;
        // 遍历需要显示的模板
        for (int i = 0; i < labelBeans.length; i++) {
            TempLabelBean labelBean = (TempLabelBean) labelBeans[i];
            // 没两个新增一行，并将指针指向新增行
            if (i % 2 == 0) {
                container = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.view_label_text_2,
                        templateFillArea, false);
                templateFillArea.addView(container);
            }
            int index = i % 2;
            ViewGroup viewGroup = (ViewGroup) container.getChildAt(index);
            TextView label = (TextView) viewGroup.getChildAt(0);
            TextView text = (TextView) viewGroup.getChildAt(1);
            label.setText(labelBean.getContent());
            // 接飞标记
            boolean JFFlag = MessageModel.IAS_FLIGHT_QUERY.equals(labelBean.getUrl());
            try {
                Log.i("C_REFLECT", "get attr: " + labelBean.getType() + " -> " + labelBean.getContent());
                Method method = FlightQueryValue.class.getMethod("get" + labelBean.getType());
                String val = (String) method.invoke(flightQueryValue, new Object[]{});
                if (labelBean.getType().equals("JST") || labelBean.getType().equals("JET") || labelBean.getType().equals("JAT")
                        || labelBean.getType().equals("STO") || labelBean.getType().equals("ETO") || labelBean.getType().equals("ATO")) {
                    val = S.FormatTime2(val);
                }
                text.setText(val);
                // 接飞做特殊处理
                if (JFFlag) {
                    Method method2 = FlightQueryValue.class.getMethod("getJFK");
                    final String JFK = (String) method2.invoke(flightQueryValue, new Object[]{});
                    if (S.isNotEmpty(JFK)) {
                        text.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                        text.setTextColor(getResources().getColor(R.color.p_bule));
                        text.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                queryFlightRelated(JFK);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询接飞航班
     *
     * @param JFK
     */
    private void queryFlightRelated(String JFK) {
        Intent intent = new Intent(this, SearchInfoActivity.class);
        intent.putExtra(EXTRA_FLIGHT_JFK, JFK);
        intent.putExtra(EXTRA_FLIGHT_AOD, AOD);
        intent.putExtra(EXTRA_TITLE, getString(R.string.jfFlight));
        startActivity(intent);
    }

    /**
     * 资源申请对话框
     */
    private void taskDialog() {
        if (rtp_map == null) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.noResources), false);
        } else {
            Object[] keySet = rtp_map.keySet().toArray();
            final String[] strings = new String[keySet.length];
            for (int i = 0; i < strings.length; i++) {
                strings[i] = (String) keySet[i];
            }
            new AlertDialog.Builder(this).setTitle(getString(R.string.resourcesType)).setIcon(android.R.drawable.ic_dialog_info)
                    .setSingleChoiceItems(strings, 0, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            check2applyTask(strings[which], rtp_map.get(strings[which]));
                            // applyTask(rtp_map.get(strings[which]));
                        }
                    }).setNegativeButton(getString(R.string.cancel), null).show();
        }
    }

    /**
     * 申请前检查确认工作,一定条件下确认方可工作
     *
     * @param sRnm
     * @param sRtp
     */
    private void check2applyTask(final String sRnm, final String sRtp) {
        // 点击确认申请的回调
        DialogInterface.OnClickListener applyTaskListener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                applyTask(sRtp);
            }
        };
        // 各种需要确认的条件，参照老版实现
        String fkeExistMsg = checkFkeExist(sRnm, sRtp);
        if (S.isNotEmpty(fkeExistMsg)) {
            showConfirmDialog(fkeExistMsg, applyTaskListener);
            return;
        } else {
            String taskCountMsg = checkTaskNum(sRtp);
            if (S.isNotEmpty(taskCountMsg)) {
                showConfirmDialog(taskCountMsg, applyTaskListener);
                return;
            }
        }
        // 最终都要申请任务
        applyTask(sRtp);
    }

    /**
     * 检测当前航班所具有的任务数
     *
     * @param sRtp
     * @return
     */
    public String checkTaskNum(final String sRtp) {
        List<FlightQueryTaskInfo> taskInfos = flightQueryValue.getTaskInfos();
        try {
            if (flightQueryValue.getTaskInfos() != null) {
                int length = taskInfos.size();
                for (int i = 0; i < length; i++) {
                    FlightQueryTaskInfo taskInfo = taskInfos.get(i);
                    if (S.valueOf(taskInfo.getServiceid()).equals(sRtp)) {
                        int taskCount = Integer.parseInt(taskInfo.getTaskcount());
                        if (taskCount > 0) {
                            return getString(R.string.SIA_1) + taskInfo.getServicenm() + getString(R.string.SIA_2) + taskCount + getString(R.string.SIA_3);
                        }
                    }
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检测是否已经存在此航班的任务
     *
     * @param sRnm
     * @param sRtp
     * @return
     */
    public String checkFkeExist(final String sRnm, final String sRtp) {
        // 检测工作任务列表
        LinkedHashMap<String, Task> workList = DataManager.getInstance().getWorkTaskList();
        Collection<Task> workCollection = workList.values();
        List<Task> taskWorkList = new ArrayList<Task>(workCollection);
        for (Task task : taskWorkList) {
            // 如果航班号、资源类型都相同
            if (flightQueryValue.getFKE().equals(task.getTaskInfo().getFKE())
                    && sRtp.equals(task.getTaskInfo().getRTP())) {
                return getString(R.string.SIA_4) + sRnm + getString(R.string.SIA_5);
            }
        }
        // 检测接收任务列表
        LinkedHashMap<String, Task> receiveList = DataManager.getInstance().getReceiveTaskList();
        Collection<Task> receiveCollection = receiveList.values();
        List<Task> taskReceiveList = new ArrayList<Task>(receiveCollection);
        for (Task task : taskReceiveList) {
            // 如果航班号、资源类型都相同
            if (flightQueryValue.getFKE().equals(task.getTaskInfo().getFKE())
                    && sRtp.equals(task.getTaskInfo().getRTP())) {
                return getString(R.string.SIA_4) + sRnm + getString(R.string.SIA_5);
            }
        }
        return null;
    }

    /**
     * 弹出确认申请对话框，点击确认执行传入回调
     *
     * @param msg
     * @param positiveCallback
     */
    private void showConfirmDialog(String msg, DialogInterface.OnClickListener positiveCallback) {
        new AlertDialog.Builder(this).setTitle(getString(R.string.prompt)).setIcon(android.R.drawable.ic_dialog_info).setMessage(msg)
                .setPositiveButton(getString(R.string.apply), positiveCallback).setNegativeButton(getString(R.string.cancel), null).create().show();
    }

    /**
     * 申请任务
     *
     * @param rtl：资源编号
     */
    protected void applyTask(String rtl) {
        TerminalapplytaskRequest requestBody = new TerminalapplytaskRequest();
        requestBody.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.TTRQ));
        TerminalApplyTaskRequestVO requestVO = new TerminalApplyTaskRequestVO();
        requestVO.setRtp(rtl);
        requestVO.setFke(flightQueryValue.getFKE());
        requestBody.setTerminalApplyTaskRequestVO(requestVO);
        Request<TerminalapplytaskResponse> request = null;
        try {
            request = new GsonRequest<TerminalapplytaskResponse>(
                    RestfulUri.getUri(MessageModel.TTRQ), TerminalapplytaskResponse.class, DataManager.getInstance().getMapper().writeValueAsString(requestBody),
                    applyTaskSuccessCallback, this.onErrCalback);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        request.setRetryPolicy(new DefaultRetryPolicy(50000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);
    }

    @SuppressLint("InflateParams")
    private void initActionBarSearchInfo() {
        actionBar.setCustomView(
                LayoutInflater.from(SearchInfoActivity.this).inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        String title = getIntent().getExtras().getString(EXTRA_TITLE);
        TextView titleVeiw = (TextView) findViewById(R.id.txt_title);
        if (S.isNotEmpty(title)) {
            titleVeiw.setText(title);
        } else {
            titleVeiw.setText(R.string.SearchInfoActivity);
        }
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(SearchInfoActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    /**
     * Toast一个消息，一段时间后退出当前Activity
     *
     * @param msg           弹出消息内容
     * @param delayedMillis 延迟时间
     */
    private void finishDelayedAfterToast(String msg, long delayedMillis) {
        if (S.isNotEmpty(msg)) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
        }
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                finish();
            }
        }, delayedMillis);
    }

    public void setORGNM(String ORGNM) {
        if (S.isNotEmpty(ORGNM)){
            try {
                this.ORGNM.setText(ORGNM.substring(4, ORGNM.length()));
                this.setORG3(ORGNM.substring(0, 3));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setDESNM(String DESNM) {
        if (S.isNotEmpty(DESNM)) {
            try {
                this.DESNM.setText(DESNM.substring(4, DESNM.length()));
                this.setDES3(DESNM.substring(0, 3));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setORG3(String ORG3) {
        this.ORG3.setText(ORG3);
    }

    public void setDES3(String DES3) {
        this.DES3.setText(DES3);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != requestQueue)
            requestQueue.stop();
    }
}